package com.lngsyz.file.util;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Base64;

import javax.imageio.ImageIO;

import org.springframework.web.multipart.MultipartFile;

import com.lngsyz.file.exception.RequestSystemException;

public class FileUtil {

	public static File convertMultipartFileToFile(MultipartFile file) throws Exception {
	    File convFile = null;
	    if (file != null && file.getSize() > 0) {
	        InputStream inputStream = file.getInputStream();
	        convFile = new File(file.getOriginalFilename());
	        FileOutputStream fos = new FileOutputStream(convFile);
	        int bytesRead = 0;
	        byte[] buffer = new byte[8192];
	        while ((bytesRead = inputStream.read(buffer)) != -1) {
	            fos.write(buffer, 0, bytesRead);
	        }
	        fos.close();
	        inputStream.close();
	        return convFile;
	    } else {
	    	throw new RequestSystemException("File is empty or its size is zero, please check!");
	    }
	}
	
	public static byte[] fileToByte(File file) throws Exception {  
        FileInputStream fis = null;
        byte[] byteArray = null;
        try {
            fis = new FileInputStream(file);
            byteArray = new byte[(int) file.length()];
            int bytesRead = fis.read(byteArray);
            if (bytesRead != file.length()) {
                throw new IOException("无法完全读取文件");
            }
        } catch(Exception e) {
        	e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return byteArray; 
    }
	
	public static String fileToBase64(String filePath) {
		String rtn = null;
		try {
			// 读取文件字节
			byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
			// Base64编码
			rtn = Base64.getEncoder().encodeToString(fileBytes);
		} catch(Exception e) {
			
		}
		return rtn;
	}
	
	public static String urlToBase64(String url) {
		String rtn = null;
		try {
			// 读取文件字节
			URL urlObj = new URL(url);
			BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));
			String content = "";
			String line;
			// 逐行读取内容
			while((line = reader.readLine()) != null) {
				content += line;
			}
			// 关闭流
			reader.close();
			// Base64编码
			rtn = Base64.getEncoder().encodeToString(content.getBytes());
		} catch(Exception e) {
			
		}
		return rtn;
	}
	
	public static byte[] urlToBytes(String imageUrl) {
		byte[] rtn = null;
		try {
			rtn = HttpUtils.download(imageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
		return rtn;
	}
	
	public static String bytesToBase64(byte[] bytes) {
		String rtn = null;
		if(bytes != null) {
			try {
				rtn = Base64.getEncoder().encodeToString(bytes);
			} catch(Exception e) {
				
			}
		}
		return rtn;
	}
	
	public static File byteToTempFile(byte[] byteArray, String fileName, String suffix) throws Exception {
		File file = File.createTempFile(fileName, suffix);
		try (FileOutputStream fos = new FileOutputStream(file)) {
			fos.write(byteArray);
		}
		return file;
	}
	
	public static void inputStreamToLocal(InputStream inputStream, String localPath) {
        try (FileOutputStream outputStream = new FileOutputStream(localPath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
	}
	
	public static boolean bytesToLocalPath(byte[] data, Path path) {
		boolean rtn = false;
		try {
			// 确保父目录存在，如果不存在则创建
            if (path.getParent() != null && !Files.exists(path.getParent())) {
                Files.createDirectories(path.getParent());
            }
		    Files.write(path, data);
		    rtn = true;
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return rtn;
	}
	
	public static boolean bytesToLocal(byte[] data, String localPath) {
        FileOutputStream fileOutputStream = null;
        boolean flag = false;
        try {
        	if(data != null) {
        		// 确保父目录存在，如果不存在则创建
        		Path path = Paths.get(localPath);
        		if (path.getParent() != null && !Files.exists(path.getParent())) {
        			Files.createDirectories(path.getParent());
        		}
        		fileOutputStream = new FileOutputStream(new File(localPath));
        		fileOutputStream.write(data);
        		flag = true;
        	}
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }
	
	public static byte[] pathToBytes(Path path) throws IOException {
		return Files.readAllBytes(path);
	}
	
	public static byte[] localToBytes(File file) throws IOException {
	    FileInputStream fis = null;
	    ByteArrayOutputStream bos = null;
	    byte[] resultBytes = null;
	    try {
	        fis = new FileInputStream(file);
	        bos = new ByteArrayOutputStream();
	        byte[] bytes = new byte[1024];
	        int len;
	        while((len = fis.read(bytes))!=-1){
	            bos.write(bytes,0,len);
	        }
	        resultBytes = bos.toByteArray();
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        bos.close();
	        fis.close();
	    }
	    return  resultBytes;
	 }
	
	public static BufferedImage bytesToBufferedImage(byte[] imageData) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(imageData);
        BufferedImage image = ImageIO.read(bis);
        bis.close();
        return image;
    }
	
	public static OutputStream bytesToOutputStream(byte[] byteArray) throws Exception {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 将字节数组写入到输出流
    	byteArrayOutputStream.write(byteArray);
        return byteArrayOutputStream;
	}
	
	public static void deleteDirectoryRecursively(Path path) throws IOException {
        if (Files.notExists(path)) {
            return;
        }

        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    throw exc;
                }
            }
        });
    }
	
	public static void main(String[] args) {
		String imageUrl = "https://218.60.149.205:80/img/download/2024-03-14/8b2c408e51724a0188975364655a6a72.png";
		String localPath = "D:/GC/sss.png";
		try {
			byte[] imgBytes = HttpUtils.download(imageUrl);
			ImageUtil.writeBytes(imgBytes, localPath);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
